﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using NHibernate.Expression;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;

namespace SimplePMT
{
    public partial class TaskSearch : Components.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(TaskSearch), this.Page);
            ValidateSession();
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string Search(string SearchBy, string SearchFor)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                List<Data.Task> taskList = new List<Data.Task>();

                if (SearchBy.Equals("ID"))
                {
                    Data.Task task = Data.Task.Find(Convert.ToInt32(SearchFor));
                    taskList.Add(task);
                }
                else if (SearchBy.Equals("Notes"))
                {
                    Data.TaskNote[] notes = Data.TaskNote.FindAll(Expression.Like("Notes", SearchFor, MatchMode.Anywhere));
                    foreach (Data.TaskNote note in notes)
                    {
                        if (!taskList.Contains(note.Task))
                        {
                            taskList.Add(note.Task);
                        }
                    }
                }
                else
                {
                    Data.Task[] tasks = Data.Task.FindAll(Expression.Like(SearchBy, SearchFor, MatchMode.Anywhere));
                    foreach (Data.Task task in tasks)
                    {
                        taskList.Add(task);
                    }
                }

                foreach (Data.Task task in taskList)
                {
                    int tci = 0;
                    Data.TaskContainerItem[] tca = Data.TaskContainerItem.FindAllByProperty("TaskID", task.ID);
                    if (tca.Length > 0)
                    {
                        tci = tca[0].TaskContainer.ID;
                    }
                    sb.Append("<a class=\"href\" href=\"javascript:OnClick=openModal('TaskView.aspx?id=" + task.ID + "&cid=" + tci + "', 'SimplePMT - " + task.Title.Replace("'", "\\'").Replace("\"", "&quot;") + "');\">" + task.Title + "</a><br><table><tr><td></td></tr></table>");
                }
                return sb.ToString();
            }
            catch
            {
                throw new Exception("Task not found");
            }
        }
    }
}
